package chemical_formula.interpreter;

import chemical_formula.token.Token;

public class Lexer {
    private final String text;
    private int pos;
    private Character currentChar;

    public Lexer(String text) {
        this.text = text;
        this.pos = 0;
        this.currentChar = text.charAt(pos);
    }

    private void advance() {
        pos++;
        if (pos > text.length() - 1) {
            this.currentChar = null;
        } else {
            this.currentChar = text.charAt(pos);
        }
    }

    private int integer() {
        StringBuilder sb = new StringBuilder();
        while (currentChar != null && Character.isDigit(currentChar)) {
            sb.append(currentChar);
            this.advance();
        }
        return Integer.parseInt(sb.toString());
    }

    private String element() {
        StringBuilder sb = new StringBuilder();
        sb.append(currentChar);
        this.advance();
        if (currentChar != null && Character.isLetter(currentChar) && Character.isLowerCase(currentChar)) {
            sb.append(currentChar);
            this.advance();
        }
        return sb.toString();
    }

    private boolean isSpace(char c) {
        return c == ' ' || c == '\t';
    }

    private void skipWhitespace() {
        while (this.currentChar != null && isSpace(this.currentChar)) {
            this.advance();
        }
    }

    public Token getNextToken() {
        while (currentChar!=null) {
            if (isSpace(currentChar)) {
                skipWhitespace();
                continue;
            }
            if (Character.isDigit(currentChar)) {
                int num = integer();
                return new Token(Token.TokenType.INTEGER,num);
            }
            if (Character.isLetter(currentChar)) {
                String elemStr = element();
                return new Token(Token.TokenType.ELEMENT, elemStr);
            }
            if (currentChar == '(') {
                this.advance();
                return new Token(Token.TokenType.LPAREN, null);
            }
            if (currentChar == ')') {
                this.advance();
                return new Token(Token.TokenType.RPAREN, null);
            }
            if (currentChar == '='){
                this.advance();
                return new Token(Token.TokenType.EQUAL, null);
            }
            if (currentChar == '+') {
                this.advance();
                return new Token(Token.TokenType.PLUS, null);
            }
        }
        return new Token(Token.TokenType.EOF, null);
    }
}
